<template>
	<view class="wrap">
		<!-- 标题区 -->
		<view class="write_title">
			<input type="text" v-model="title" placeholder="请输入标题"/>
		</view>
		 <!-- 内容展示区 -->
		 <view class="artList">
			 <block v-for="(item,index) in artList" :key='index'>
				 <!-- 图片-->
				 <view class="item" v-if="item.type == 'image'">
					 <image :src="item.content" :data-index="index" mode="widthFix" @tap="removeImg"></image>
				 </view>
				 <!-- 文本-->
				 <view class="item" v-if="item.type == 'text'">
					<textarea :value="item.content" placeholder=""/>
				 	<view :data-index="index" class="deleteText" @tap="deleteText">删除</view>
				 </view>
			 </block>
		 </view>
		 <!-- 输入区-->
		 <form @submit="submit">
			 <view class="inputArea">
				 <view class="addImg" @tap="addImg">+图片</view>
				 <view class="addText">
					<textarea name="artText" maxlength="-1" v-model="inputContent" placeholder="请输入文本"></textarea>
					<button type="primary" form-type="submit">添加</button>
				 </view>
			 </view>
		 </form>
		 <!-- 选择分类 -->
		 <view class="art-cate">
			 <view>文章分类</view>
			 <view class="">
				 <picker mode="selector" :range="caties" @change="cateChange">
					 <view>{{caties[currentCateIndex]}}</view>
				 </picker>
			 </view>
		 </view>
		  <!-- 提交按钮 -->
		  <view class="submitNow" v-if="artList.length > 0" @tap="submitNow">发布文章</view>
	</view>
</template>

<script>
	var _self, loginRes;
	var signModel = require('../../commons/sign.js');
	export default {
		data() {
			return {
				title: '',
				artList: [],
				inputContent: '',
				needUploadImg: [], // 需要上传的图片
				uploadIndex: 0,   // 上传图片的个数
				// 分类
				caties: ['点击选择'],
				currentCateIndex: 0,
				catiesFromApi: [],
				// 记录真实选择的api接口数据的分类id
				sedCateIndex: 0
			}
		},
		methods: {
			cateChange: function (e) {
				console.log("****"+JSON.stringify(e));
				var sedIndex = e.detail.value;
				this.currentCateIndex = sedIndex;
				// 获取选择的分类的名称
				if (sedIndex < 1) {
					return;
				}
				var cateName = this.caties[sedIndex];
				for (var k in this.catiesFromApi) {
					if (cateName == this.catiesFromApi[k].cateName) {
						this.sedCateIndex = k;
						break
					}
				}
				this.currentCateIndex = sedIndex;
			},
			removeImg: function (e) {
				var index = e.currentTarget.dataset.index;
				uni.showModal({
					content: "确定要删除此图片吗",
					title: '提示',
					success(e) {
						if(e.confirm){
							_self.artList.splice(index,1);
						}
					}
				})
			},
			deleteText : function(e){
			    var index = e.currentTarget.dataset.index;
			    uni.showModal({
			        content:"确定要删除吗",
			        title:'提示',
			        success(e) {
			            if (e.confirm) {
			                _self.artList.splice(index, 1);
			            }
			        }
			    });
			},
			submit: function (res) {
				var content = res.detail.value.artText;
				if (content.length < 1) {
					uni.showToast({
						title: '请输入内容',
						icon: 'none'
					});
					return;
				}
				this.artList.push({
					"type": "text",
					"content": content
				});
				this.inputContent = '';
			},
			addImg: function () {
				uni.chooseImage({
				    count: 1,
				    sizeType: ['compressed'],
				    success: function(res) {
						console.log("tempFilePaths:"+res.tempFilePaths[0]);
				        _self.artList.push({"type":"image", "content" : res.tempFilePaths[0]})
				    }
				})
			},
			submitNow: function () {
				// 数据校验
				if (this.title.length < 2) {
					uni.showToast({
						title: '请输入标题，至少2个字符',
						icon: 'none'
					});
					return;
				}
				if (this.artList.length < 1) {
					uni.showToast({
						title: '请填写文章内容',
						icon: 'none'
					});
					return;
				}
				if (this.sedCateIndex < 1) {
					uni.showToast({
						title: '请选择分类',
						icon: 'none'
					});
					return;
				}
				// 上传图片 一次一个多次上传 [ 递归函数 ]
				// 上传完成后整体提交数据
				// 首先整理一下需要上传的图片
				this.needUploadImg = [];
				for (var i = 0; i < this.artList.length; i++) {
					if (this.artList[i].type == 'image') {
						this.needUploadImg.push({
							"tmpurl": this.artList[i].content,
							"indexID": i
						});
					}
				}
				this.uploadImg();
			},
			uploadImg: function () {
				if (this.needUploadImg.length < 1 || this.uploadIndex >= this.needUploadImg.length) {
					// 图片已经上传完成，可以提交文章了
					uni.showLoading({
						title: '正在提交'
					});
					// 将信息整合后提交到服务器
					var sign = uni.getStorageSync('sign');
					uni.request({
						url: this.apiServer + 'addInfo',
						method: 'POST',
						header: {'content-type' : "application/x-www-form-urlencoded"},
						data: {
						    title   : _self.title,						// 文章标题
						    content : JSON.stringify(_self.artList),	// 图片的地址
						    cate    : _self.sedCateIndex,				// 文章分类
							openId	: loginRes[1]						// 该服务商唯一用户标识
						},
						success: (res) => {
							console.log("success:"+JSON.stringify(res));
							if (res.data.code == '200') {
								uni.showToast({
									title: '提交成功！',
									icon: 'none'
								});
								// 清空数据
								_self.artList = [];
								signModel.sign(_self.apiServer);
								// 防止数据缓存
								_self.currentCateIndex = 0;
								_self.sedCateIndex     = 0;
								_self.needUploadImg    = [];
								_self.title            = '';
								setTimeout(function () {
									uni.switchTab({
										url: '../my/my'
									})
								},1000);
							} else{
								uni.showToast({title:res.data.msg, icon:"none"});
								
							}
						},
						fail: (res) => {
							
						},
						complete: () => {
							
						}
					});
					return;
				} else {
					//图片上传
					uni.showLoading({
						title: '上传图片'
					});
					var uploader = uni.uploadFile({
						url		:	_self.apiServer + '/upload/image',
						filePath:	_self.needUploadImg[_self.uploadIndex].tmpurl,
						name	:	'file',
						success: (uploadFileRes) => {
							uploadFileRes = JSON.parse(uploadFileRes.data);
							console.log("上传："+JSON.stringify(uploadFileRes));
							if (uploadFileRes.code != '200') {
								console.log(uploadFileRes);
								uni.showToast({title:"上传图片失败,请重试!", icon:"none"});
								return false;
							}
							// 将已经上传的文件地址赋值给文章数据
							var index = _self.needUploadImg[_self.uploadIndex].indexID;
							// 将图片的地址存储
							_self.artList[index].content = _self.staticServer + uploadFileRes.data;
							console.log(_self.artList); 
							_self.uploadIndex ++;
							// 递归上传
							setTimeout(function(){_self.uploadImg();}, 1000);
						},
						fail: () => {
						    uni.showToast({title:"上传图片失败,请重试!", icon:"none"});
						}
					})
				}
			}
		},
		onLoad: function(){
			_self = this;
			// token验签
			signModel.sign(this.apiServer);
			loginRes = this.checkLogin("../write/write",'2');
			if(!loginRes){
				//return 或终止函数运行哦！
				console.log("终止函数运行哦");
				return false;
			}
			// 将信息整合后提交到服务器
			var sign = uni.getStorageSync('sign');
			console.log("加载文章分类:"+sign);
			uni.request({
				url: this.apiServer+'getCate',
				method: 'GET',
				data: {
					sign : sign
				},
				success: (res) => {
					if (res.data.code == 200) {
						// 把数据格式整理为 picker 支持的格式 ['分类名', ...]
						console.log(JSON.stringify(res.data.data));
						var categories = res.data.data;
						for (var k in categories) {
							_self.caties.push(categories[k].cateName);
						}
						// 记录分类信息
						_self.catiesFromApi = categories;
					}
				}
			})
		}
	}
</script>

<style>

</style>
